import * as c from '@/services/consts';
import * as api from '@/services/geoip';
import * as utils from '@/utils/utils';
import { ArrowRightOutlined, ClockCircleOutlined, PlusOutlined, UnlockTwoTone } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { useModel } from 'umi';
import { Badge, Button, Popconfirm, Tag, Tooltip } from 'antd';
import React, { useRef, useState } from 'react';
import FormIsp from './FormIsp';
import FormArea from './FormArea';
import FormIp from './FormIp';
import FlagImage from '@/components/FlagImage';

const List: React.FC = (props: any) => {
  // const { match } = props;
  // console.log(match, props);
  //console.log(history?.location?.state, utils.getStateValue("pagecurrent") );

  const actionRef = useRef<ActionType>();
  const { hasRight } = useModel('useAuthModel');

  const [formOpen, setFormOpen] = useState<boolean>(false);
  const [formIspOpen, setFormIspOpen] = useState<boolean>(false);
  const [formIpOpen, setFormIpOpen] = useState<boolean>(false);
  const [current, setCurrent] = useState<API.GeoipIsp | undefined>(undefined);
  const [currentParent, setCurrentParent] = useState<API.GeoipIsp | undefined>(undefined);
  const [listType, setListType] = useState<string>('isp');
  
  const {
    reloadGeoipIsps,
  } = useModel('useGlobalModel', (model) => ({
    reloadGeoipIsps: model.reloadGeoipIsps,
  }));

  // const loadData = async (
  //   params: any,
  //   sort: Record<string, SortOrder>,
  //   filter: Record<string, (string | number)[] | null>,
  // ) => {
  //   const result = await api.list(params, sort, filter);

  //   if (result && result.success) {
  //     // setCurPage(result.current);
  //     // console.log(result.current);
  //   }

  //   return result;
  // };


  
  const handleFormIspSubmit = async (record: API.GeoipIsp) => {
    if(currentParent){
      record.geoipId = currentParent.geoipId;
    }
    let result: API.Result;
    if (current) {
      result = await api.ispupdate({
        ...current,
        ...record,
      });
    } 
    else {
      result = await api.ispadd({ ...record });
    }

    if (result && result.success === true) {
      setCurrent(undefined);
      setCurrentParent(undefined);
      setFormIspOpen(false);
      actionRef.current?.reload();
      reloadGeoipIsps();
    }
  };

  const handleRemove = async (id: string) => {
    const result = await api.ispremove({ key: id });
    if (result.success) {
      actionRef.current?.reload();
      reloadGeoipIsps();
    }
  };
  

  let columns: ProColumns<API.GeoipIsp | API.GeoipIp>[] = [
    {
      title: '地区',
      dataIndex: 'geoipName',
      sorter: true,
      search: false,
      hideInTable: listType == "ip",
      width: 200,
      render: (_, record) => {
        return <><FlagImage flagName={record.geoip?.flag} />{record.geoip?.name}</>;
      },
      // renderText(_, record) {
      //   return record.geoip?.name;
      // },
    },
    {
      title: '名称',
      dataIndex: 'name',
      hideInTable: listType == "ip",
      hideInSearch: listType == "ip",
      sorter: true,
    },
    {
      title: 'IP',
      dataIndex: 'ip',
      width:160,
      hideInTable: listType != "ip",
      hideInSearch: listType != "ip",
      render: (_, record) => {
        return record.subnetMask > 0 ? <>{record.ip}/{record.subnetMask}</> : record.ip;
      },
    },
    {
      title: '起始IP',
      dataIndex: 'ipEnd',
      width:150,
      search: false,
      hideInTable: listType != "ip",
      hideInSearch: listType != "ip",
      render: (_, record) => {
        return record.ipStart != record.ipEnd ? <>{record.ipStart}</> : '';
      },
    },
    {
      title: '结束IP',
      dataIndex: 'ipEnd',
      width:150,
      search: false,
      hideInTable: listType != "ip",
      hideInSearch: listType != "ip",
      render: (_, record) => {
        return record.ipStart != record.ipEnd ? <>{record.ipEnd}</> : '';
      },
    },
    {
      title: 'ISP',
      dataIndex: 'isp',
      // width:200,
      search: false,
      hideInTable: listType != "ip",
      hideInSearch: listType != "ip",
      render: (_, record) => {
        return record.geoipIsp ? <>{record.geoipIsp.geoip ? <><Tag color='blue'>{record.geoipIsp.geoip.name}</Tag><ArrowRightOutlined /> </> : ''}
        {record.geoipIsp.parent ? <><Tag color='blue'>{record.geoipIsp.parent?.name}</Tag><ArrowRightOutlined /> </> : ''}
        <Tag color='blue'>{record.geoipIsp?.name}</Tag></> : '';
      },
    },
    {
      title: '备注',
      dataIndex: 'remark',
      sorter: true,
      search: false,
      ellipsis: true,
    },
  ];

  columns = columns.concat([
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 220,
      hideInTable: listType == "ip",
      render: (_, record) => {
        let cmps = [];
        
        if (hasRight('geoip_ispupdate')) {
          cmps.push(
            <a
              onClick={() => {
                setFormIspOpen(true);
                setCurrent(record);
                setCurrentParent(undefined);
              }}
            >
              编辑
            </a>,
          );
        }

        if (hasRight('geoip_ispdelete')) {
          cmps.push(
            <Popconfirm
              key="delete"
              title="确定要删除吗?"
              onConfirm={async () => {
                await handleRemove(record.id);
              }}
            >
              <a>删除</a>
            </Popconfirm>,
          );
        }
        
        if (hasRight('geoip_ispcreate')) {
          cmps.push(
            <a
              onClick={() => {
                setFormIspOpen(true);
                setCurrent(undefined);
                setCurrentParent(record);
              }}
            >
              新建子ISP
            </a>,
          );
        }
        
        if (hasRight('geoip_iplist')) {
          cmps.push(
            <a
              onClick={() => {
                setFormIpOpen(true);
                setCurrent(record);
                setCurrentParent(undefined);
              }}
            >
              IP管理
            </a>,
          );
        }

        return cmps;
      },
    },
  ]);
  
  let subColumns: ProColumns<API.GeoipIsp | API.GeoipIp>[] = [
    {
      title: '名称',
      dataIndex: 'name',
      sorter: true,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      sorter: true,
      search: false,
      ellipsis: true,
    },
  ];

  subColumns = subColumns.concat([
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 150,
      hideInTable: listType == "ip",
      render: (_, record) => {
        let cmps = [];
        
        if (hasRight('geoip_ispupdate')) {
          cmps.push(
            <a
              onClick={() => {
                setFormIspOpen(true);
                setCurrent(record);
                setCurrentParent(record.parent);
              }}
            >
              编辑
            </a>,
          );
        }

        if (hasRight('geoip_ispdelete')) {
          cmps.push(
            <Popconfirm
              key="delete"
              title="确定要删除吗?"
              onConfirm={async () => {
                await handleRemove(record.id);
              }}
            >
              <a>删除</a>
            </Popconfirm>,
          );
        }
        
        if (hasRight('geoip_iplist')) {
          cmps.push(
            <a
              onClick={() => {
                setFormIpOpen(true);
                setCurrent(record);
                setCurrentParent(record.parent);
              }}
            >
              IP管理
            </a>,
          );
        }

        return cmps;
      },
    },
  ]);

  return (
    <PageContainer>
      <ProTable
        rowKey="id"
        actionRef={actionRef}
        columns={columns}
        search={{
          span: 5,
          collapsed: false,
        }}
        toolbar={{
          multipleLine: true,
          menu: {
            type: 'tab',
            activeKey: listType,
            items: [{label:'ISP列表', key:'isp'},{label:'IP列表', key:'ip'}],
            onChange: (tabKey) => {
              //console.log('tabKey', tabKey);
              setListType(tabKey as string);
              // actionRef.current?.reset();
            },
          },
        }}
        toolBarRender={() => {
          var toolbarDoms: any[] = [];
          
          if (hasRight('geoip_create')) {
            toolbarDoms.push(
              <Button
                type="primary"
                key="create"
                onClick={() => {
                  setFormOpen(true);
                }}
              >
                <PlusOutlined />
                管理IP地区
              </Button>
            );
          }

          if (hasRight('geoip_ispcreate')) {
            toolbarDoms.push(
              <Button
                type="primary"
                key="create"
                onClick={() => {
                  setFormIspOpen(true);
                  setCurrent(undefined);
                  setCurrentParent(undefined);
                }}
              >
                <PlusOutlined />
                新建ISP
              </Button>
            );
          }

          return toolbarDoms;
        }}
        pagination={{
          defaultPageSize: 50,
          pageSizeOptions: [
            '50',
            '100',
            '200',
            '300',
            '500',
          ],
          hideOnSinglePage: false,
          defaultCurrent: Number(utils.getStateValue('pagecurrent') ?? 1),
        }}
        params={{listType}}
        request={listType == 'ip' ? api.iplist : api.isplist}        
        expandable={listType == 'ip' ? undefined :{
          expandedRowRender: (record) => ( 
            <ProTable
              columns={subColumns}
              headerTitle={false}
              search={false}
              options={false}
              dataSource={record.childs}
              tableStyle={{ marginLeft: 10 }}
              pagination={{
                defaultPageSize: 50,
                pageSizeOptions: [
                  '50',
                  '100',
                  '200',
                  '300',
                  '500',
                ],
                hideOnSinglePage: false,
              }}
            />
          ),
          defaultExpandedRowKeys: ['0'],
        }}
      />
      

      <FormArea
        open={formOpen}
        onCancel={() => {
          setFormOpen(false);
        }}
      />
      <FormIp
        open={formIpOpen}
        current={current}
        currentParent={currentParent}
        onCancel={() => {
          setCurrent(undefined);
          setCurrentParent(undefined);
          setFormIpOpen(false);
        }}
      />
      <FormIsp
        open={formIspOpen}
        onSubmit={handleFormIspSubmit}
        current={current}
        parent={currentParent}
        onCancel={() => {
          setFormIspOpen(false);
          setCurrentParent(undefined);
          setCurrent(undefined);
        }}
      />
    </PageContainer>
  );
};

export default List;
